<template>
  <div
    class="map_wrapper"
  >
    <div id="map"></div>
    <!-- <van-button id="drawRect" type="primary" @click="setMode('drawRect')">矩形标注</van-button> -->
    <!-- <div class="btn_polygon" v-if="isShowDis != true">
      <van-button
        id="drawPoint"
        v-if="featureType === 'Point' || featureType === 'All'"
        @click="setMode('drawPoint')"
        >绘制点</van-button
      >
      <van-button id="drawPolygon" v-else @click="setMode('drawPolygon')"
        >选择区域</van-button
      >
    </div> -->
    <!-- <van-button id="drawMask" type="primary" @click="setMode('drawMask', '#FF0000', 5)">红线</van-button>
    <van-button id="clearMask" type="primary" @click="setMode('clearMask')">檫除</van-button>-->
  </div>
</template>

<script>
import AILabel from 'ailabel'

export default {
  components: {},
  props: {
    featureType: {
      type: String,
      default: 'Polygon'
    },
    // 多边形点位
    areaPoints: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 圆点点位
    points: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 图片
    pointImg: {
      type: String,
      default:
        'http://211.152.62.6:10093/profile/upload/tenantMg/2021/05/29/654bf7b1-790a-4a59-9ca0-72c3188a5f82.jpg'
    },
    // 是否隐藏操作没传默认展示按钮
    isShowDis: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      gMaskLayer: '',
      Mode: 'pan',
      gFeatureLayer: '',
      gMap: '',
      mappingStyles: {
        clearMask: {
          drawStyle: { lineWeight: 10 },
          featureStyle: {}
        },
        drawPoint: {
          drawStyle: { pointRadius: 20 },
          featureStyle: {
            strokeColor: '#0000FF',
            fillColor: '#8B008B',
            opacity: 1,
            pointRadius: 15
          }
        },
        drawPolygon: {
          drawStyle: {
            fillColor: '#dd0a00',
            lineWeight: 2,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          },
          featureStyle: {
            fillColor: '#dd0a00',
            lineWeight: 2,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          }
        }
      }
    }
  },

  updated () {},
  computed: {},
  methods: {
    setMode (mode, color, size) {
      const preCurrentMode =
        mode.indexOf('drawMask') === 0
          ? 'drawMask'
          : mode.indexOf('Roi') !== -1
            ? 'drawRoi'
            : mode
      const currentMode =
        preCurrentMode.indexOf('drawPolygon') === 0
          ? 'drawPolygon'
          : preCurrentMode
      const drawStyle = {
        strokeColor: '#dd0a00',
        opacity: 1,
        lineWeight: 1
      }
      if (color) {
        if (currentMode === 'drawPolygon') {
          drawStyle.strokeColor = '#dd0a00'
        } else {
          drawStyle.fillColor = '#dd0a00'
        }
        drawStyle.lineWeight = 2
        drawStyle.opacity = 1
      }
      if (size) {
        drawStyle.lineWeight = size
      }
      this.Mode = currentMode
      this.gMap && this.gMap.setMode(currentMode, new AILabel.Style(drawStyle)) // 设置当前模式（模式名，样式）
    }
  },
  created () {
    // console.log(this.points, this.areaPoints)
  },
  mounted () {
    this.gMap = new AILabel.Map('map', {
      zoom: 1080,
      cx: 0,
      cy: 0,
      zoomMax: 650 * 10,
      zoomMin: 650 / 10,
      autoFeatureSelect: this.featureType !== 'All'
    })
    this.gImageLayer = new AILabel.Layer.Image(
      'img',
      this.pointImg,
      { w: 1080, h: 720 },
      { zIndex: 1 }
    )
    this.gMap.addLayer(this.gImageLayer)
    this.gFeatureLayer = new AILabel.Layer.Feature('featureLayer', {
      zIndex: 3,
      transparent: false
    })

    this.gMap.addLayer(this.gFeatureLayer)
    this.gMaskLayer = new AILabel.Layer.Mask('maskLayer', {
      zIndex: 2,
      opacity: 0.8
    })
    this.gMap.addLayer(this.gMaskLayer)
    // 如果是编辑状态，此处需要执行数据回填操作
    if (this.featureType === 'Point') {
      this.areaPoints.map((item) => {
        let fea = new AILabel.Feature.Point(
          item.id,
          item.points,
          {
            name: '中国'
          },
          item.featureStyle
        )
        this.gMap.setMode('pan', item.featureStyle)
        this.gFeatureLayer.addFeature(fea)
      })
    } else if (this.featureType === 'All') {
      if (this.points) {
        this.points.map((item) => {
          let fea = new AILabel.Feature.Point(
            item.id,
            item.points,
            {
              name: '中国'
            },
            item.featureStyle
          )
          this.gMap.setMode('pan', item.featureStyle)
          this.gFeatureLayer.addFeature(fea)
        })
      }

      if (!this.areaPoints) {
        return
      }
      this.areaPoints.map((item) => {
        let fea = new AILabel.Feature.Rect(
          item.id,
          // points,
          item.points,
          {
            name: '中国'
          },
          {
            fillColor: 'red',
            lineWeight: 1,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          }
        )
        // 将页面设置为可操作状态
        this.gMap.setMode('pan', item.featureStyle)
        this.gFeatureLayer.addFeature(fea)
      })
    } else {
      if (!this.areaPoints) {
        return
      }
      this.areaPoints.map((item) => {
        let fea = new AILabel.Feature.Rect(
          item.id,
          // points,
          item.points,
          {
            name: '中国'
          },
          {
            fillColor: 'red',
            lineWeight: 1,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          }
        )
        // 将页面设置为不可编辑状态
        this.gMap.setMode('pan', item.featureStyle)
        this.gFeatureLayer.addFeature(fea)
      })
    }

    // 选中方法
    this.gMap.events.on('featureSelected', (feature) => {
      window.gMap.mLayer.removeAllMarkers()
      if (
        this.featureType === 'All' &&
        this.areaPoints.map((item) => item.id).indexOf(feature.id) > -1
      ) {
        return
      }
      console.log('click')
      this.id = feature.id
      let cFeature = feature
      // 删除按钮添加
      const featureBounds = cFeature.getBounds()
      const leftTopPoint = featureBounds[0] // 边界坐上角坐标
      let deleteMarker = new AILabel.Marker(`marker-${cFeature.id}`, {
        src: require('@/assets/icons/delete.png'),
        x: leftTopPoint.x,
        y: leftTopPoint.y,
        offset: {
          x: 0,
          y: 0
        },
        featureId: cFeature.id
      })
      window.gMap.mLayer.addMarker(deleteMarker)

      // 删除方法
      deleteMarker.regEvent('click', () => {
        // 执行选中元素删除
        let arr = []
        this.areaPoints.map((item) => {
          if (item.id !== this.id) {
            arr.push(item)
          }
        })
        this.$emit('input', arr)

        this.gFeatureLayer.removeFeatureById(this.id)
        // 对应删除标注层中删除（x）icon
        window.gMap.mLayer.removeAllMarkers()
      })
    })
    // 总添加方法，下面可以划分类型，根据类型去执行添加
    this.gMap.events.on('geometryDrawDone', (type, points) => {
      // console.log(points,type,9999)
      this.pointsArray = points

      const timestamp = new Date().getTime()

      // const featureStyle = this.mappingStyles[cMode].featureStyle

      // 元素添加展示
      if (type === 'rect') {
        // 生成元素唯一标志（时间戳）
        const fea = new AILabel.Feature.Rect(
          `feature-${timestamp}`,
          points,
          {
            name: '中国'
          },
          {
            fillColor: 'red',
            lineWeight: 1,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          }
        )
        this.gFeatureLayer.addFeature(fea)
      } else if (type === 'mask') {
        // 包含绘制&涂抹事件
        const maskAction = points
        this.gMaskLayer.addMaskAction(maskAction)
      }
      if (type === 'point') {
        const featureStyle = {
          fillColor: 'red',
          lineWeight: 1,
          opacity: 0.5,
          strokeColor: '#dd0a00'
        }
        let fea = new AILabel.Feature.Point(
          `feature-${timestamp}`,
          points,
          {
            name: '中国'
          },
          featureStyle
        )
        this.gFeatureLayer.removeAllFeatures()
        if (this.featureType === 'All') {
          // 重新绘制区域，否则会被清空
          this.areaPoints.map((item) => {
            let fea = new AILabel.Feature.Rect(
              item.id,
              // points,
              item.points,
              {
                name: '中国'
              },
              {
                fillColor: 'red',
                lineWeight: 1,
                opacity: 0.3,
                strokeColor: '#dd0a00'
              }
            )
            // 将页面设置为可操作状态
            this.gMap.setMode('pan', item.featureStyle)
            this.gFeatureLayer.addFeature(fea)
            this.setMode('drawPoint')
          })
          this.gFeatureLayer.addFeature(fea)
        }
        let params = {
          id: `feature-${timestamp}`,
          points,
          featureStyle
        }
        this.$emit('input', [params])
      }
      // 多边形
      if (type === 'polygon') {
        let fea = new AILabel.Feature.Polygon(
          `feature-${timestamp}`,
          points,

          {
            name: '中国'
          },
          {
            fillColor: 'red',
            lineWeight: 2,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          }
        )
        this.gFeatureLayer.addFeature(fea)
        let params = {
          id: `feature-${timestamp}`,
          points,
          featureStyle: {
            fillColor: 'red',
            lineWeight: 1,
            opacity: 0.3,
            strokeColor: '#dd0a00'
          }
        }
        this.$emit('input', [...this.areaPoints, params])
      }
    })
    // feature-reset监听
    // this.gMap.events.on('featureStatusReset', () => {
    //   gMap.mLayer.removeAllMarkers()
    // })
    // 编辑图形
    this.gMap.events.on('geometryEditing', (type, feature, points) => {
      if (!window.gMap.mLayer) return
      const marker = window.gMap.mLayer.getMarkerById(`marker-${feature.id}`)
      if (!marker) return
      const bounds = AILabel.Util.getBounds(points)
      const leftTopPoint = bounds[0] // 边界坐上角坐标
      marker.update({ x: leftTopPoint.x, y: leftTopPoint.y })
    })
    // 可操作状态下对选中该图形进行操作
    this.gMap.events.on('geometryEditDone', (type, activeFeature, points) => {
      activeFeature.update(
        {
          points
        },
        (this.pointsArray = points)
      )
      activeFeature.show()
    })
    window.gMap = this.gMap

    // 设置编辑状态
    if (!this.isShowDis) {
      if (this.featureType === 'Point' || this.featureType === 'All') {
        this.setMode('drawPoint')
      } else {
        this.setMode('drawPolygon')
      }
    }
  }
}
</script>
<style scoped>
.map_wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}
#map {
  width: 100%;
  height: 100%;
  position: relative;
  cursor: pointer;
}
.btn_polygon {
  text-align: right;
  position: absolute;
  left: 510px;
  bottom: 30px;
}
</style>
